package com.dindang.checkline.mvp.presenter;

import android.app.Application;
import android.content.Intent;
import android.view.View;

import com.alibaba.fastjson.JSON;
import com.dindang.checkline.R;
import com.dindang.checkline.app.utils.TextTransformUtils;
import com.dindang.checkline.mvp.model.api.Api;
import com.dindang.checkline.mvp.model.entity.BaseResponse;
import com.dindang.checkline.mvp.model.entity.TaskDetail;
import com.dindang.checkline.mvp.model.entity.TaskEvent;
import com.dindang.checkline.mvp.ui.activity.ChecklineActivity;
import com.dindang.checkline.mvp.ui.activity.ErrorEndingActivity;
import com.dindang.checkline.mvp.ui.activity.LineDetailActivity;
import com.dindang.checkline.mvp.ui.activity.adapter.ProgressViewAdapter;
import com.jess.arms.integration.AppManager;
import com.jess.arms.di.scope.ActivityScope;
import com.jess.arms.mvp.BasePresenter;
import com.jess.arms.http.imageloader.ImageLoader;

import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;
import me.jessyan.rxerrorhandler.core.RxErrorHandler;
import me.jessyan.rxerrorhandler.handler.ErrorHandleSubscriber;
import me.jessyan.rxerrorhandler.handler.RetryWithDelay;

import javax.inject.Inject;

import com.dindang.checkline.mvp.contract.TaskDetailContract;
import com.jess.arms.utils.ArmsUtils;
import com.jess.arms.utils.RxLifecycleUtils;
import com.longxi.gamer_base.BaseAppConst;
import com.longxi.gamer_base.MyApplication;
import com.longxi.gamer_base.dialog.WaitDialog;
import com.longxi.gamer_base.model.MaintainDetailsEvent;
import com.longxi.gamer_base.utils.DateTimeUtils;
import com.longxi.gamer_base.utils.KeyBoardUtil;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;


/**
 * ================================================
 * Description:
 * <p>
 * Created by MVPArmsTemplate on 03/05/2019 16:39
 * <a href="mailto:jess.yan.effort@gmail.com">Contact me</a>
 * <a href="https://github.com/JessYanCoding">Follow me</a>
 * <a href="https://github.com/JessYanCoding/MVPArms">Star me</a>
 * <a href="https://github.com/JessYanCoding/MVPArms/wiki">See me</a>
 * <a href="https://github.com/JessYanCoding/MVPArmsTemplate">模版请保持更新</a>
 * ================================================
 */
@ActivityScope
public class TaskDetailPresenter extends BasePresenter<TaskDetailContract.Model, TaskDetailContract.View> {
    @Inject
    RxErrorHandler mErrorHandler;
    @Inject
    Application mApplication;
    @Inject
    ImageLoader mImageLoader;
    @Inject
    AppManager mAppManager;
    private TaskEvent mTaskEvent = new TaskEvent();
    private List<TaskDetail.EventBean> mProgressList = new ArrayList<>();
    private ProgressViewAdapter mProgressAdapter;
    private WaitDialog mWaitDialog;
    private TaskDetail.TaskDetailParam mParam = new TaskDetail.TaskDetailParam();
    private TaskDetail.ChangeStatus mAddFlowParam = new TaskDetail.ChangeStatus();
    private List<String> mStateList = new ArrayList<>();// 通过这个给数据增加处理轨迹中标红的东西 详情请看原型 不服请找后台
    private String status;//任务单的状态
    private String mPhone;
    private MaintainDetailsEvent mMaintainDetailsEvent = new MaintainDetailsEvent();
    private String id = "1";//任务单的id
    private String lineId;//路线id
    TaskDetail mData = new TaskDetail();
    String[] type = {"", "客服", "安保 ", "保洁", "环境", "品质"};
    String[] states = {"", "等待接单", "等待开始", "正在巡检", "正常结束", "异常结束", "逾期终止", "逾期未巡", "逾期结束"};

    @Inject
    public TaskDetailPresenter(TaskDetailContract.Model model, TaskDetailContract.View rootView) {
        super(model, rootView);
    }

    public void init() {
        mWaitDialog = new WaitDialog(mRootView.getActivity());
        EventBus.getDefault().register(this);
        id = mRootView.getActivity().getIntent().getStringExtra("id");
        initAdapter();
        initListener();
        quertTaskDetail(false);
    }

    /**
     * 初始化适配器
     */
    private void initAdapter() {
        mProgressAdapter = new ProgressViewAdapter(mProgressList);
        mRootView.getRvProgress().setAdapter(mProgressAdapter);
    }

    private void initListener() {
        //点击接单按钮
        mRootView.getButtonGetTask().setOnClickListener(v -> {
            if (mData.getRecord().getC_status().equals("1")) {
                changeStatus();//改变状态
            } else {
                Intent intent = new Intent(mRootView.getActivity(), ChecklineActivity.class);
                intent.putExtra("data", JSON.toJSONString(mData));
                intent.putExtra("isOrder", mData.getLine().isBOrdered());
                mRootView.getActivity().startActivity(intent);
            }
        });

        /**
         * 点击异常结束按钮
         */
        mRootView.getButtonErrorEnd().setOnClickListener(v -> goError());
/**
 * 点击查看详情按钮
 */
        mRootView.getButtonSeeDetail().setOnClickListener(v -> goSeeDetail());
    }

    private void goSeeDetail() {
        Intent intent = new Intent(mRootView.getActivity(), LineDetailActivity.class);
        intent.putExtra("data", JSON.toJSONString(mData));
        mRootView.getActivity().startActivity(intent);
    }

    private void goError() {
        Intent intent = new Intent(mRootView.getActivity(), ErrorEndingActivity.class);
        intent.putExtra("id", mData.getRecord().getL_id() + "");
        mRootView.getActivity().startActivity(intent);
    }


    /**
     * 调任务单详情接口
     */
    private void quertTaskDetail(boolean takeOrder) {
        //以下是真实调接口
        mWaitDialog.showWaitingDialog(ArmsUtils.getString(mApplication, R.string.data_load));
        mParam.id = "1";
        mModel.quertTaskDetail(mParam)
                .subscribeOn(Schedulers.io())
                .retryWhen(new RetryWithDelay(2, 2))//遇到错误时重试,第一个参数为重试几次,第二个参数为重试的间隔
                .doOnSubscribe(disposable -> {

                }).subscribeOn(AndroidSchedulers.mainThread())
                .observeOn(AndroidSchedulers.mainThread())
                .doFinally(() -> {
                    mWaitDialog.hideWaitingDialog();
                })
                .compose(RxLifecycleUtils.bindToLifecycle(mRootView))//使用 Rxlifecycle,使 Disposable 和 Activity 一起销毁
                .subscribe(new ErrorHandleSubscriber<BaseResponse<TaskDetail>>(mErrorHandler) {
                    @Override
                    public void onError(Throwable t) {
                        super.onError(t);
                        ArmsUtils.makeText(mRootView.getActivity(), t.getMessage());
                    }

                    @Override
                    public void onNext(BaseResponse<TaskDetail> response) {
                        if (response.getStatus().equals(BaseAppConst.OUT_TOKEN)) {
                            MyApplication.getInstance().gotoLoginActivity();
                        }
                        mData = response.getData();
                        setData(response, takeOrder);
                    }
                });
    }


    private void setData(BaseResponse<TaskDetail> response, boolean takeOrder) {
        mStateList.clear();
        mProgressList.clear();
        if (!response.isSuccess()) {
            ArmsUtils.makeText(mApplication, response.getStatuMsg());
            return;
        }
        mRootView.getTvLineNameValue().setText(mData.getLine().getCName());
        mRootView.getTvCheckTypeValue().setText(type[mData.getLine().getLTypeid()]);
        mRootView.getTvCheckManValue().setText(mData.getPlan().getC_officer());
        if(mData.getPlan().getC_mode().equals("0")){
            mRootView.getTvSignWayValue().setText("二维码");
        }else {
            mRootView.getTvSignWayValue().setText("二维码");
        }
        if (mData.getLine().isBOrdered()) {
            mRootView.getTvIsOrderValue().setText("有序");
        } else {
            mRootView.getTvIsOrderValue().setText("无序");
        }
        if(mData.getPlan().isB_photo().equals("1")){
            mRootView.getTvIsCameraValue().setText("是");
        }else {
            mRootView.getTvIsCameraValue().setText("否");
        }
        mRootView.getTvPlanTimeValue().setText(DateTimeUtils.dateToYearMonthDayHour(new Date(mData.getPlan().getD_start())) + "至" + DateTimeUtils.dateToYearMonthDayHour(new Date(mData.getPlan().getD_end())));
        mRootView.getTvTaskNumValue().setText(mData.getRecord().getC_no());
        mRootView.getTvProjectNameValue().setText(mData.getLine().getLBuildingName());
        status = mData.getRecord().getC_status();
        mRootView.getTvState().setText(states[TextTransformUtils.string2Int(status)]);
        showBottomBtn();
//        mProgressList.get(0).setSend_man(mData.getOfficers().get(0).getcOfficer());
        mProgressList.addAll(response.getData().getEvent());
        mProgressAdapter.setReason(mData.getRecord().getC_remark());//设置异常原因
        mProgressAdapter.notifyDataSetChanged();
        if (takeOrder) {
            Intent intent = new Intent(mRootView.getActivity(), ChecklineActivity.class);
            intent.putExtra("data", JSON.toJSONString(mData));
            mRootView.getActivity().startActivity(intent);
        }
    }

    /**
     * 底部按钮显示
     */
    public void showBottomBtn() {
        mRootView.getConstraintlayout().setVisibility(View.GONE);
        switch (status) {
            case "1":
                mRootView.getConstraintlayout().setVisibility(View.VISIBLE);
                mRootView.getButtonGetTask().setVisibility(View.VISIBLE);
                mRootView.getButtonErrorEnd().setVisibility(View.VISIBLE);
                mRootView.getButtonGetTask().setText("确认接单");
                mRootView.getButtonErrorEnd().setText("异常结束");
                break;
            case "2":
                mRootView.getConstraintlayout().setVisibility(View.VISIBLE);
                mRootView.getButtonGetTask().setVisibility(View.VISIBLE);
                mRootView.getButtonErrorEnd().setVisibility(View.VISIBLE);
                mRootView.getButtonGetTask().setText("开始巡检");
                mRootView.getButtonErrorEnd().setText("异常结束");
                break;
            case "3":
                mRootView.getConstraintlayout().setVisibility(View.VISIBLE);
                mRootView.getButtonGetTask().setVisibility(View.VISIBLE);
                mRootView.getButtonErrorEnd().setVisibility(View.VISIBLE);
                mRootView.getButtonGetTask().setText("继续巡检");
                mRootView.getButtonErrorEnd().setText("异常结束");
                break;
            case "4"://显示查看详情
                mRootView.getConstraintlayout().setVisibility(View.GONE);
                mRootView.getButtonSeeDetail().setVisibility(View.VISIBLE);
                break;
            default:
                mRootView.getConstraintlayout().setVisibility(View.GONE);
                mRootView.getButtonGetTask().setVisibility(View.GONE);
                mRootView.getButtonErrorEnd().setVisibility(View.GONE);
                break;
        }
    }


    private void changeStatus() {
        //以下是真实调接口
        mWaitDialog.showWaitingDialog(ArmsUtils.getString(mApplication, R.string.data_load));
        mAddFlowParam.id = mData.getRecord().getL_id() + "";
        mModel.changeStatus(mAddFlowParam)
                .subscribeOn(Schedulers.io())
                .retryWhen(new RetryWithDelay(0, 2))//遇到错误时重试,第一个参数为重试几次,第二个参数为重试的间隔
                .doOnSubscribe(disposable -> {

                }).subscribeOn(AndroidSchedulers.mainThread())
                .observeOn(AndroidSchedulers.mainThread())
                .doFinally(() -> {
                    mWaitDialog.hideWaitingDialog();
                })
                .compose(RxLifecycleUtils.bindToLifecycle(mRootView))//使用 Rxlifecycle,使 Disposable 和 Activity 一起销毁
                .subscribe(new ErrorHandleSubscriber<BaseResponse>(mErrorHandler) {
                    @Override
                    public void onNext(BaseResponse response) {
                        ArmsUtils.makeText(mApplication, response.getStatuMsg());
                        if (!response.isSuccess()) {
                            ArmsUtils.makeText(mRootView.getActivity(), response.getStatuMsg());
                            return;
                        }
                        if (null == mData) {
                            return;
                        }
                        quertTaskDetail(true);//刷新界面
//
                    }
                });
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        this.mErrorHandler = null;
        this.mAppManager = null;
        this.mImageLoader = null;
        this.mApplication = null;
        this.mProgressAdapter = null;
        this.mProgressList = null;
        this.mAddFlowParam = null;
        this.mParam = null;
        this.mStateList = null;
        this.mMaintainDetailsEvent = null;
        if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this);
        }
    }

    @Subscribe(threadMode = ThreadMode.POSTING)
    public void TaskRefresh(TaskEvent taskEvent) {
        quertTaskDetail(false);
    }

    private void hideKeyBorder() {
        KeyBoardUtil.hideKeyBoard(mRootView.getActivity());
    }
}
